﻿using MCPlatform.MotionLib.Base;
using MCPlatform.UI.Controls.AssistantMethods.StaticMethods;
using MCPlatform.UI.Controls.Converts;
using Panuon.WPF;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Input;

namespace MCPlatform.UI.Controls.Models
{
    public class IODataModel : NotifyPropertyChangedBase
    {
        #region Properties

        /// <summary>
        /// IO接口
        /// </summary>
        public IIO? IOEntity { get => _IOEntity; set => Set(ref _IOEntity, value); }
        private IIO? _IOEntity;

        /// <summary>
        /// IO名称
        /// </summary>
        public string? IOName { get => _IOname; set => Set(ref _IOname, value); }
        private string? _IOname;

        /// <summary>
        /// IO类型，输入或者输出
        /// </summary>
        public string? Type { get => _Type; set => Set(ref _Type, value); }
        private string? _Type;

        /// <summary>
        /// IO地址
        /// </summary>
        public ushort Address { get => _address; set => Set(ref _address, value); }
        private ushort _address;

        /// <summary>
        /// IO值
        /// </summary>
        public bool Value
        {
            get => _value;
            set => Set(ref _value, value);
        }
        private bool _value;

        public ICommand? SetValue { get => _SetValue; set => Set(ref _SetValue, value); }
        private ICommand? _SetValue;


        #endregion



        #region Methods

        public void Mapping()
        {
            if (IOEntity is null)
            {
                return;
            }
            CommonUse.AutoMapProperties(IOEntity, this);
        }

        #endregion


        #region Methods

        Timer timer;
        public void StartMappingEntityToModel()
        {
            if (IOEntity is null)
            {
                return;
            }

            timer.Start();


        }


        public void StopMappingEntityToModel()
        {

            timer.Stop();


        }

        #endregion

        #region CTOR

        public IODataModel()
        {
            timer = new Timer(200);
            timer.Elapsed += Timer_Elapsed;
            SetValue = new CommandBase(SetValueByAddress);
        }



        public void SetValueByAddress(object o)
        {
            if (IOEntity is null || Type is null || Type.Equals("I"))
            {
                return;
            }

            int OnorOff = IOEntity.ReadOutBit(Address) > 0 ? 0 : 1;
            IOEntity.WriteOutBit(Address, (ushort)OnorOff);
        }
        private void Timer_Elapsed(object? sender, ElapsedEventArgs e)
        {
            if (IOEntity is null)
            {
                return;
            }

            this.Mapping();
        }

        #endregion

    }
}
